package com.scnb.cor.servletExample;

import java.util.ArrayList;
import java.util.List;

/**
 * 责任链模式
 */

public class ServletMain {
    public static void main(String[] args) {
       Request request = new Request();
       request.str = "大家好:)，<script>，欢迎访问 mashibing.com，大家都是996 ";
       Response response = new Response();
       response.str = "";

       FilterChain chain = new FilterChain();
       chain.add(new HTMLFilter()).add(new SensitiveFilter());
       chain.doFilter(request, response, chain);
       System.out.println("request = " + request.str);
       System.out.println("response = " + response.str);
    }
}

class Msg{
    String name;
    String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "Msg{" +
                "msg='" + msg + '\'' +
                '}';
    }
}

interface Filter{
    boolean doFilter(Request request, Response response, FilterChain chain);
}

class Request{
    String str;
}

class Response{
    String str;
}

class HTMLFilter implements Filter {
    @Override
    public boolean doFilter(Request request, Response response, FilterChain chain) {
       request.str = request.str.replace("<","[").replace(">","]");
       request.str += "--HTMLFilter()";
       chain.doFilter(request, response, chain);
       response.str += "--HTMLFilter()";
       return true;
    }
}

class SensitiveFilter implements Filter {

    @Override
    public boolean doFilter(Request request, Response response, FilterChain chain) {
        request.str = request.str.replace("996", "955");
        request.str += "--SensitiveFilter()";
        chain.doFilter(request, response, chain);
        response.str += "--SensitiveFilter()";
        return true;
    }
}


/**
 * FilterChain实现了Filter接口后，则一个FilterChain对象自己本身
 * 也是一个Filter，那么main函数中执行fc1.add(fc2)就可以了（此时把fc2看做Filter）
 */
class FilterChain implements Filter {
    List<Filter> filters = new ArrayList<>();
    //记录当前执行到了哪个filter
    int index = 0;

    //该add函数返回this指针，就可进行链式编程了
    public FilterChain add(Filter f){
        filters.add(f);
        return this;
    }

    public boolean doFilter(Request request, Response response, FilterChain chain) {
        if (index == filters.size()){
            return false;
        }
        Filter f = filters.get(index);
        index++;
        f.doFilter(request, response, chain);
        return true;
    }
}
